import io from 'socket.io-client'
import {setSocket, setUnread} from '../actions'
import {post} from '../common/js/utils'

export function chatWebSocket(store) {
  const socket = io.connect('/chat')
  let lastSocketId

  // 监听state变化
  store.subscribe(function() {
    const state = store.getState()
    if (lastSocketId === state.socketInfo.id) return
    if (state.userInfo.status === 1 && state.socketInfo.id) {
      lastSocketId = state.socketInfo.id
      // 登录webSocket
      post('/socket/login', {id: state.socketInfo.id}).then(res => {}).catch(() => {})
    }
  })

  socket.on('receive message', (message) => {
    if (typeof window.receiveMessage === 'function') {
      window.receiveMessage(message)
    }
    if (typeof window.refreshDialogs === 'function') {
      window.refreshDialogs()
    }
  })
  socket.on('unread count', (count) => {
    store.dispatch(setUnread(count))
  })

  socket.on('connect', () => {
    window.chatWebSocket = socket
    store.dispatch(setSocket({
      id: socket.id
    }))
  })

  socket.on('disconnect', (reason) => {
    if (reason === 'io server disconnect') {
      // the disconnection was initiated by the server, you need to reconnect manually
      socket.connect()
    }
    // else the socket will automatically try to reconnect
  })
  return socket
}
